package yongxin.controller.tasks;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import yongxin.entity.process.ProcessEntity;
import yongxin.entity.process.ProcessJsonEntity;
import yongxin.entity.process.ProcessNodeJsonEntity;
import yongxin.entity.processreport.ProcessReportEntity;
import yongxin.entity.tasks.TasksEntity;
import yongxin.service.process.ProcessServiceI;
import yongxin.service.processreport.ProcessReportServiceI;
import yongxin.service.tasks.TasksServiceI;

/**   
 * @Title: Controller
 * @Description: 工序汇报任务单
 * @author zhangdaihao
 * @date 2015-02-05 11:44:08
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/tasksControllers")
public class CopyOfTasksController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CopyOfTasksController.class);

	@Autowired
	private TasksServiceI tasksService;
	@Autowired
	private ProcessServiceI processService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ProcessReportServiceI processReportService;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 工序汇报任务单列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "tasks")
	public ModelAndView tasks(HttpServletRequest request) {
		String type = request.getParameter("type");
		request.setAttribute("type", type);
		if(StringUtil.isEmpty(type)){
		return new ModelAndView("yongxin/tasks/tasksList");
		}else{
	    return new ModelAndView("yongxin/reports/rateReportList");	
		}
	}  

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(TasksEntity tasks,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TasksEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tasks, request.getParameterMap());
		this.tasksService.getDataGridReturn(cq, true);
	    String total_trzl = String.valueOf(tasksService.findOneForJdbc("select sum(CONVERT(numeric(19,2),fweight)) as sum_trzl from t_tasks").get("sum_trzl"));
		
		dataGrid.setFooter("fstate:重量总计,"+ "fbcph:"+ total_trzl +",fyclh:合计,fweight");
		//dataGrid.setFooter("fyclh:合计,fweight");
		TagUtil.datagrid(response, dataGrid);
	}

	
	/**
	 * 成材率报表
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "rate_datagrid")
	public void rate_datagrid(TasksEntity tasks,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		String type = request.getParameter("type");
		CriteriaQuery cq = new CriteriaQuery(TasksEntity.class, dataGrid);
		//查询条件组装器
		if(type.equals("S")){
		cq.like("fbcph", type+"%");	
		}else if(type.equals("Y")){
		cq.like("fbcph", type+"%");		
		}
		//cq.add(Restrictions.eq("fstate", "1"));
		cq.eq("fstate", "1");
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tasks, request.getParameterMap());
		this.tasksService.getDataGridReturn(cq, true);
		
		dataGrid.setFooter("fyclh:合计,fweight");
		TagUtil.datagrid(response, dataGrid);
	}
	/**
	 * 删除工序汇报任务单
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(TasksEntity tasks, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		tasks = systemService.getEntity(TasksEntity.class, tasks.getFid());
		message = "工序汇报任务单删除成功";
		tasksService.delete(tasks);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加工序汇报任务单
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(TasksEntity tasks, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		if (StringUtil.isNotEmpty(tasks.getFid())) {
			message = "工序汇报任务单更新成功";
			TasksEntity t = tasksService.get(TasksEntity.class, tasks.getFid());
			try {
				MyBeanUtils.copyBeanNotNull2Bean(tasks, t);
				tasksService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
			} catch (Exception e) {
				e.printStackTrace();
				message = "工序汇报任务单更新失败";
			}
		} else {
			message = "工序汇报任务单添加成功";
			tasksService.save(tasks);
			
			
			ProcessReportEntity processReport=new ProcessReportEntity();
			processReport.setCprocess("p9");			
			processReport.setFbcph(tasks.getFbcph());
			processReport.setFtrhd(tasks.getFthick());
			processReport.setFtrkd(tasks.getFwidth());
			processReport.setFtrzl(tasks.getFweight());
			processReport.setFworkshop(tasks.getFworkshop());	
			processReport.setFstate("0");
			processReport.setCreateBy("");
			processReport.setCreateDate(null);
			processReportService.save(processReport);
			
			
			
			
			ProcessEntity entity=new ProcessEntity();
			entity.setFbcph(tasks.getFbcph());
			entity.setFprocess("p1");
			processService.save(entity);
			
			ProcessEntity entity2=new ProcessEntity();
			entity2.setFreportid(processReport.getId());
			entity2.setFbcph(tasks.getFbcph());
			entity2.setFprocess("p9");
			entity2.setFiscurrent(1);
			processService.save(entity2);
			
			
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 工序汇报任务单列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(TasksEntity tasks, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(tasks.getFbcph())) {
			//tasks = tasksService.getEntity(TasksEntity.class, tasks.getFid());
			req.setAttribute("tasksPage", tasks);
		}
		return new ModelAndView("yongxin/tasks/tasks");
	}
	
	
	/**
	 * 工序汇报任务单列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "edit")
	public ModelAndView edit(TasksEntity tasks, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(tasks.getFid())) {
			tasks = tasksService.getEntity(TasksEntity.class, tasks.getFid());
			req.setAttribute("tasksPage", tasks);
		}
		return new ModelAndView("yongxin/tasks/edit_tasks");
	}
	
	
	
	/**
	 * 添加工序汇报
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "getProcess")
	@ResponseBody
	public AjaxJson getProcess(ProcessReportEntity processReport, HttpServletRequest request) {
	
		
		String fbcph=request.getParameter("fbcph");
		Object[] object=new Object[2];
		object[0]=fbcph;
		object[1]=fbcph+"-%";
		
		String sql="select tp.fbcph,tp.fprocess,tp.create_date,dic.typename,tp.freportid from t_process tp ";
		sql +=" left join (select tst.typecode,tst.typename from t_s_type tst,t_s_typegroup tstg ";
		sql +=" where tst.typegroupid=tstg.ID ";
		sql +=" and tstg.typegroupcode='ccgx') dic ";
		sql +=" on tp.fprocess=dic.typecode ";
		sql +=" where fbcph=? or fbcph like ? ";
		sql +=" order by tp.create_date ";
		
		
		ProcessJsonEntity processJsonEntity=null;
		 try{
			 List<Map<String,Object>> maplist=systemService.findForJdbc(sql, object);
			 processJsonEntity= getProcessJson(maplist);
		 }
		 catch(Exception ex){
			 ex.printStackTrace();
		 }
		 finally{
			
		 }
		 AjaxJson j = new AjaxJson();
		 j.setObj(processJsonEntity);
		 
		return j;
	}
	
	
	private ProcessJsonEntity getProcessJson(List<Map<String,Object>> list){
		
		//demo_node_1:{name:"任务单<br>(YJ1503001)",left:67,top:71,type:"start",width:150,height:24},
		ProcessJsonEntity processJsonEntity=new ProcessJsonEntity();
		for (Map<String, Object> map : list) {
			String fbcph=map.get("fbcph").toString();
			String fprocess=map.get("fprocess").toString();
			String ftypename=map.get("typename").toString();
			String freportid=map.get("freportid")==null ? "" : map.get("freportid").toString();
			
			String nodename=ftypename+"<br>("+fbcph+")";
			
			
			ProcessNodeJsonEntity node=new ProcessNodeJsonEntity();
			node.setFbcph(fbcph);
			node.setName(nodename);
			node.setType("node");
			node.setProcess(fprocess);
			
			Object[] object=new Object[1];
			object[0]=fbcph;
			
			String sql="select fwlname '物料名称',fylghs '原料供应商',fyclh '原厂炉号',fweight '重量',fthick '厚度',fwidth '宽度' from t_tasks where fbcph=? ";
			if(StringUtil.isNotEmpty(freportid)){
				object[0]=freportid;
				sql="select fmatchinegroup '机组',ftrhd '投入厚度',ftrkd '投入宽度',ftrzl '投入重量',fcchd '产出厚度', fcckd '产出宽度', fcczl '产出重量',fbfzl '报废重量',frate '成材率' from t_processreport where id=? ";
			}
			
			 try{
				 List<Map<String,Object>> maplist=systemService.findForJdbc(sql, object);
				 String details=getProcessDetailJson(maplist);
				 node.setDetails(details);
			 }
			 catch(Exception ex){
				 node.setDetails("没有数据...");
			 }
			
			processJsonEntity.addNode(node);
			
		}
		
		
		
		return processJsonEntity;
	}
	
	
	private String getProcessDetailJson(List<Map<String,Object>> list){
		
		String jsonString = JSON.toJSONString(list);
		jsonString=jsonString.replaceAll(",", "<br>");
		jsonString=jsonString.replaceAll("\"", "");
		jsonString=jsonString.replaceAll("[{}\\[\\]]", "");
		jsonString=jsonString.concat("<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
				"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
				"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
				"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		return jsonString;
	}
	
}
